package com.stardata.liangshisq.tcslmon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stardata.liangshisq.tcslmon.entity.UserToken;
import com.stardata.liangshisq.tcslmon.mapper.TokenMapper;
import com.stardata.liangshisq.tcslmon.service.TokenService;
import com.stardata.liangshisq.tcslmon.util.CharUtil;
import lombok.AllArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Samson Shu
 * @email shush@stardata.top
 * @date 2020/6/5 10:14
 */
@Service
@AllArgsConstructor
public class TokenServiceImpl extends ServiceImpl<TokenMapper, UserToken>
    implements TokenService {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  private final TokenMapper tokenMapper;
  /**
   * 30天过期
   */
  private final static Long EXPIRE_HOURS = 8L;

  public UserToken getByToken(@NotNull String token) {
    Map<String, Object> map = new HashMap<>();
    map.put("token", token);
    List<UserToken> result = tokenMapper.selectByMap(map);
    return result.isEmpty() ? null : result.iterator().next();
  }

  public Map<String, Object> createToken(@NotNull Long userId) {
    //生成一个token
    String token = CharUtil.getRandomString(32);
    //当前时间
    LocalDateTime now = LocalDateTime.now();

    //过期时间
    LocalDateTime expireTime = now.plusHours( EXPIRE_HOURS );

    //判断是否生成过token
    UserToken userToken = getById(userId);
    if (userToken == null) {
      userToken = new UserToken();
      userToken.setUserId(userId);
      userToken.setToken(token);
      userToken.setUpdateTime(now);
      userToken.setExpireTime(expireTime);

      //保存token
      save(userToken);
    } else {
      userToken.setToken(token);
      userToken.setUpdateTime(now);
      userToken.setExpireTime(expireTime);

      //更新token
      updateById(userToken);
    }

    Map<String, Object> map = new HashMap<>();
    map.put("token", token);
    map.put("expire", EXPIRE_HOURS  * 3600);

    return map;
  }
}
